<style lang="less">

</style>

<template>
  <div >
    <el-form :model="queryForm" label-width="114px" :rules="rules" ref="addform" label-suffix="：">
      <el-row :getter="10">
        <el-col :span="12">
          <el-form-item :label="$t('internship.internshipBase')" prop="baseName">
            <el-input v-model="queryForm.baseName" maxlength="64"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('internship.baseLevel')" prop='baseLevel'>

            <el-select v-model="queryForm.baseLevel" @change="changeCollege"  style="width: 100%" >
                <el-option
                    v-for="item in options.degreeType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :getter="10">
        <el-col :span="12">
          <el-form-item :label="$t('internship.proviCity')" prop="provinceCity">
            <!-- <el-autocomplete
            class="inline-input"
            v-model="state1"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete> -->
            <!-- <el-input v-model="queryForm.provinceCity" maxlength="64"></el-input> -->
            <SelectTree2 ref='proviCity' v-model="queryForm.provinceCity" @change='changeInput' :labelDate="queryForm.provinceCity?queryForm.provinceCity:null"  style="width:100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('internship.address')" prop="address">
            <el-input v-model="queryForm.address" maxlength="128"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :getter="10">
        <el-col :span="12">
          <el-form-item :label="$t('internship.representative')" prop="legalPresident">
            <!-- @change="changeRepre" -->
            <el-input v-model="queryForm.legalPresident"  maxlength="64" clearable></el-input>
            
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('internship.stopState')" prop="isEnabled">
            <el-select  v-model="queryForm.isEnabled" style="width: 100%">
                <el-option label="启用" :value="1"> </el-option>
                <el-option label="停用" :value="0"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :getter="10">
        <el-col :span="12">
          <el-form-item :label="$t('internship.effectiveDate')" size="small" prop="startTime">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.startTime"
              :picker-options="pickerOptionsStart"
              type="date"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('internship.effectiveEnd')" size="small" prop="endTime">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.endTime"
              :picker-options="pickerOptionsEnd"
              type="date"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :getter="10">
        <el-col :span="12">
          <el-form-item :label="$t('internship.baseContact')" label-width="118px" prop="baseContactPerson">
            <el-input v-model="queryForm.baseContactPerson" maxlength="16"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('internship.baseNumber')" label-width="118px" prop="baseContactPhone">
            <el-input v-model="queryForm.baseContactPhone" maxlength="11"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :getter="10">
        <el-col :span="12">
          <el-form-item :label="$t('internship.baseEmail')" prop="baseContactEmail">
            <!-- @change="changeEmail" -->
            <el-input  v-model="queryForm.baseContactEmail"  maxlength="64"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('graduate.college')" :prop="queryForm.baseLevel==='1'?'':collegeAcademy">
            <DictSelect clearable style="width: 100%"
              v-model="queryForm.collegeAcademy"
              filterable
              
              :plzSelect="$t('internship.pleaseSelect')"
              :data="options.faculty" >
            </DictSelect>
          </el-form-item>
        </el-col>
       
      </el-row>
      <el-row :getter="10">
        <el-col :span="12">
          <el-form-item :label="$t('internship.schoolContact')" prop="collegeContactPerson">
            <!-- @change="checkSpecial" -->
            <el-input  v-model="queryForm.collegeContactPerson"   maxlength="16"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('internship.schoolNumber')" >
            <el-input  v-model="queryForm.collegeContactPhone" @change="changeNum" maxlength="11"></el-input>
          </el-form-item>
        </el-col>
       
      </el-row>
      <el-row :getter="10">
        <el-col :span="12">
          <el-form-item :label="$t('internship.adjunct')" prop="enclosureFileName">
            <el-upload
              class="upload-demo"
              v-model="queryForm.enclosureFileName"
              action="api/commonservice/obsfile/uploadfile"
              :headers="{'X-Token': $store.state.session.sessionid}"
              :data="{bucketname: 'face', folderpath: 'file'}"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :limit="1"
              :on-success="handleSuccess"
              :file-list="fileList">
              <!-- 
              :limit="3" enclosureFile-->
              <el-button size="small" type="primary">{{$t('internship.selectFile')}}</el-button>
              <div v-if='deleting' slot="tip" class="el-upload__tip">{{$t('internship.againDeleting')}}</div>
              <!-- v-if='deleting'<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :getter="10">
        <el-form-item :label="$t('internship.internshipIntroduc')"  prop="introduction">
          <el-input
            maxlength="256"
            type="textarea"
            :rows="5"
            v-model="queryForm.introduction" >
          </el-input>
        </el-form-item>
      </el-row>
      <el-row :getter="10">
        <!-- :disabled="dataProp!=='新增'&&dataProp!=='编辑'" -->
        <el-form-item :label="$t('internship.remark')" prop="remark">
          <el-input
            maxlength="256"
            type="textarea"
            :rows="5"
            v-model="queryForm.remark">
          </el-input>
        </el-form-item>
      </el-row>
    </el-form>
    <el-dialog
      width="25%"
      ref="innerDialog"
      :title="$t('graduateBase.prompt')"
      :visible.sync="innerVisible"
      append-to-body
      :top="'28vh'">
      <div style="text-align: left;margin-bottom: 25px;">{{$t('graduateBase.cancelTip')}}</div>
      <div style="text-align: right;">
        <el-button type="primary" @click="confirmInner">{{$t('common.btn.confirm')}}</el-button>
        <el-button @click="cancelInner">{{$t('common.btn.cancel')}}</el-button>
        <el-button type="primary" @click="confirmAndClose">{{$t('graduateBase.saveAndClose')}}</el-button>
      </div>
    </el-dialog>
    <el-row type="flex" class="row-bg" justify="end">
      <el-button @click="cancelDialog" >{{$t('graduate.cancel')}}</el-button>
      <!-- <el-button @click="cancelDialog" v-if='dataProp==="特殊编辑"'>{{$t('graduate.cancel')}}</el-button> -->
      <el-button type="danger"  @click="conserve">{{$t('graduate.conserve')}}</el-button>
      <el-button type="danger"  @click="affirmForm" >{{$t('graduate.submit')}}</el-button>
    </el-row>

  </div>
</template>

<script>
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import SelectTree2 from 'common/src/views/graduateStudent/component/SelectTree2';
export default {
  components: {
    SelectTree2: SelectTree2
  },
  props: {
    
    dataListObj: {
      type: String
    },
    dataProp: {
      type: String
    },
    dataListProp: {
      type: Object
    },
    showFlag: {
      type: Boolean
    },
    agent: {
      type: Boolean,
      default: false,
      required: false
    },
    admin: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    
    let validateNum = (rule, value, callback) => {
      // let reg = /^[0-9]*$/;
      let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!reg.test(value) || value === '') {
        return callback(new Error(this.$t('mainbase.pleasePhone')));
      }
      return callback();
    };
    let validateEmail = (rule, value, callback) => {
      // let reg = /^[0-9]*$/;
      let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!reg.test(value) || value === '') {
        return callback(new Error(this.$t('mainbase.pleasEmail')));
      }
      return callback();
    };
    let validateCity = (rule, value, callback) => {
      let reg = /[`$]/im;
      if (value === '' || value == null) {
        return callback(new Error(this.$t('graduate.pleaseSelect'),));
      } else if (reg.test(value)) {
        return callback(new Error(this.$t('identificationToDoList.cannotContain')));
      }
      return callback();
    };
    let cannotContain = (rule, value, callback) => {
      let reg = /[`$]/im;
      if (reg.test(value)) {
        return callback(new Error(this.$t('identificationToDoList.cannotContain')));
      } else if (value === '') {
        return callback(new Error(this.$t('internship.pleaseEnter')));
      }
      return callback();
    };
    return {
      dataList: [],
      fileList: [],
      collegeAcademy: 'collegeAcademy',
      innerVisible: false,
      deleting: false,
      queryForm: {
        startTime: null,
        endTime: null,
        baseName: '',
        baseLevel: '',
        provinceCity: '',
        address: '',
        legalPresident: '',
        isEnabled: 1,
        baseContactPerson: '',
        baseContactPhone: '',
        baseContactEmail: '',
        collegeAcademy: '',
        collegeContactPhone: '',
        enclosureFileUrl: '',
        enclosureFileName: '',
        status: '',
        collegeContactPerson: ''
      },
      auths: [], // 按钮权限
      options: {
        faculty: [],
        degreeType: []
      },
      pickerOptionsStart: {
        disabledDate: time => {
          let endDateVal = this.queryForm.endTime;
          if (endDateVal) {
            // return time.getTime() > endDateVal;
            return time.getTime() > new Date(endDateVal).getTime();
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          let beginDateVal = this.queryForm.startTime;
          if (beginDateVal) {
            // return time.getTime() < beginDateVal;
            return time.getTime() <= new Date(beginDateVal).getTime()- 86400000;
          }
        }
      },
      rules: {
        baseName: [
          { required: true, validator: cannotContain, trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: this.$t('graduate.pleaseSelect'), trigger: 'change' }
        ],
        endTime: [
          { required: true, message: this.$t('graduate.pleaseSelect'), trigger: 'change' }
        ],
        baseLevel: [
          { required: true, message: this.$t('graduate.pleaseSelect'), trigger: 'change' }
        ],
        isEnabled: [
          { required: true, message: this.$t('graduate.pleaseSelect'), trigger: 'change' }
        ],
        provinceCity: [
          { required: true, message: this.$t('graduate.pleaseSelectCity'), trigger: 'change' },
          { validator: validateCity, trigger: 'change' } 
        ],
        enclosureFileName: [
          { required: true, message: this.$t('internship.attachment'), trigger: 'change' } 
        ],
        baseContactEmail: [
          { required: true, validator: validateEmail, trigger: 'blur' } 
        ],
        collegeContactPerson: [
          { validator: this.checkSpecial, trigger: 'blur' } 
        ],
        remark: [
          { validator: this.checkSpecial, trigger: 'blur' } 
        ],
        introduction: [
          { validator: this.checkSpecial, trigger: 'blur' } 
        ],
        legalPresident: [
          { validator: this.checkSpecial, trigger: 'blur' } 
        ],
        address: [
          { required: true, validator: cannotContain, trigger: 'blur' } //"请选择证件类型"
        ],
        baseContactPhone: [
          { required: true, validator: validateNum, trigger: 'blur' } 
        ],
        baseContactPerson: [
          { required: true, validator: cannotContain, trigger: 'blur' } 
        ],
        collegeAcademy: [
          { required: true, message: this.$t('graduate.pleaseSelect'), trigger: 'change' } 
        ],
        
      },
      
    };
  },
  watch: {
    showFlag: {
      handler: function(newV, oldV) {
        if (newV) {
          this.$refs['addform'].clearValidate();
          if (this.dataListProp) {
            if (this.dataProp === '新增') {
              this.fileList = [];
              this.queryForm.isEnabled = 1;
            } else {
              this.queryForm = JSON.parse(JSON.stringify(this.dataListProp));
              this.fileList.push({ name: this.dataListProp.enclosureFileName });
            }
            // this.queryForm = JSON.parse(JSON.stringify(this.dataListProp));
            // this.fileList.push({ name: this.dataListProp.enclosureFileName });
          } 
        } else {
          this.fileList = [];
          // this.queryForm = {};
          for (let key in this.queryForm) {
            if (key === 'startTime') {
              this.queryForm.startTime = null;
            } else if (key === 'endTime') {
              this.queryForm.endTime = null;
            } else {
              this.queryForm[key] = '';
            }
          }
          // this.$refs['addform'].resetFields();
          this.$refs['addform'].clearValidate();
        }
      }
    }
  },
  // async beforeCreate() {
  //   this.source.language = await kindo.util.getLanguage('certificateTypeLang');
  // },
  methods: {
    changeInput(val, data) {
      data.forEach(el => {
        if (el.label.indexOf(val) < 0) {
          this.queryForm.provinceCity = '';
          // this.$refs.proviCity.cancelDialog();
        }
      });
      if (!val) {
        this.queryForm.provinceCity = '';
      }
    },
   
    // 过滤$符号
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        return callback(new Error(this.$t('identificationToDoList.cannotContain')))
      } else if (value === '') {
        return callback();
      } else {
        return callback();
      }
    },
    // 过滤$符号
    checkRemark(val) {
      if (this.queryForm.remark.indexOf("$") >= 0) {
        this.queryForm.remark = '';
        return this.$message({
          type: "error",
          message: this.$t('identificationToDoList.cannotContain')
        });
      }
    },
    // 过滤$符号
    checkIntroduc(val) {
      if (this.queryForm.introduction.indexOf("$") >= 0) {
        this.queryForm.introduction = '';
        return this.$message({
          type: "error",
          message: this.$t('identificationToDoList.cannotContain')
        });
      }
    },
    // 过滤$符号
    // checkSpecial(val) {
    //   if (this.queryForm.collegeContactPerson.indexOf("$") >= 0) {
    //     this.queryForm.collegeContactPerson = '';
    //     return this.$message({
    //       type: "error",
    //       message: this.$t('identificationToDoList.cannotContain')
    //     });
    //   }
    // },
    // 过滤$符号
    changeRepre(val) {
      if (this.queryForm.legalPresident.indexOf("$") >= 0) {
        this.queryForm.legalPresident = '';
        return this.$message({
          type: "error",
          message: this.$t('identificationToDoList.cannotContain')
        });
      }
    },
    // 字典获取
    getOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ['JDJB', 'X_YX']
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            degreeType: "JDJB",
            faculty: "X_YX"
          },
          res.data,
          this.options
        );
      });
    },
    // 输入网址
    changeEmail(val) {
      // console.log(val);
      let re = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (val) {
        if (re.test(val)) {
          return this.queryForm.baseContactEmail = val;
          // return true;
        }else{
          this.$message(this.$t('mainbase.pleasEmail'));
          this.queryForm.baseContactEmail = '';
        }
      }
    },
    // 校验学校联系人电话
    changeNum(val) {
      let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (val) {
        if (reg.test(val)) {
          return this.queryForm.collegeContactPhone = val;
          // return true;
        }else{
          this.$message(this.$t('mainbase.pleasePhone'));
          this.queryForm.collegeContactPhone = '';
        }
      }
    },
    changeSelect(val) {
      // console.log(val, '112');
      this.dataList.forEach(el => {
        if (val === el.id) {
          this.queryForm.calendarYear = el.year;
          this.queryForm.calendarTerm = el.term;
          this.queryForm.calendarName = el.fullName;
        }
      });
    },
    changeCollege(val) {
      this.queryForm.collegeAcademy = '';
      if (val === '1') {
        this.rules.collegeAcademy[0].required = false;
      } else {
        this.rules.collegeAcademy[0].required = true;
      }
    },
    // 内层弹出确定
    confirmInner() {
      this.$refs['addform'].resetFields();
      this.dataListProp = {};
      for (const key in this.queryForm) {
        if (this.queryForm[key] === 'startTime') {
          this.queryForm.startTime = null;
        } else if (this.queryForm[key] === 'endTime') {
          this.queryForm.endTime = null;
        } else {
          this.queryForm[key] = "";
        }
      }
      this.queryForm.provinceCity = '';
      this.fileList = [];
      this.$refs.proviCity.cancelDialog();
      this.deleting = false;
      this.innerVisible = false;
      this.$emit("cancel-dialog", false);
    },
    // 内层弹出取消
    cancelInner() {
      this.innerVisible = false;
    },
    // 内层弹出保存关闭
    confirmAndClose() {
      this.innerVisible = false;
      this.conserve();
    },
    // 取消
    cancelDialog() {
      let isEmpty = true;
      for (let key in this.queryForm) {
        if (this.queryForm[key]) {
          isEmpty = false;
        }
      }
      if (isEmpty) {
        this.innerVisible = false;
        // this.$refs['addform'].resetFields();
        this.deleting = false;
        this.$emit("cancel-dialog", false);
      } else {
        this.innerVisible = true;
      }
     
    },
    // 重置
    reset() {
      this.$emit("cancel-dialog", false);
    },
    // 提交
    affirmForm() {
      // console.log(this.queryForm);
      this.$refs['addform'].validate(valid => {
        if (valid) {
          this.queryForm.status = 1;
          let obj = Object.assign({}, this.queryForm);
          this.$emit("affirm-form", obj, 'conserve', this.dataListObj); 
          this.deleting = false;
          
        }
      });
    },
    proviCityDialog() {
      this.$refs.proviCity.cancelDialog();
    },
    // 保存
    conserve() {
      // if (this.dataProp === '新增') {
      this.$refs['addform'].validate(valid => {
        if (valid) {
          if (this.dataProp === '新增') {

            this.queryForm.status = 0;
            let obj = Object.assign({}, this.queryForm);
            this.$emit("affirm-form", obj, 'conserve', this.dataListObj); 
            this.deleting = false;
          } else if (this.dataProp === '编辑') {
            let obj = Object.assign({}, this.queryForm);
            this.$emit("affirm-form", obj, 'conserve', this.dataListObj); 
            this.deleting = false;
          }
        }
      });
      // }
    },
    // 上传之前
    handleChange() {},
    // 删除
    handleRemove() {
      this.queryForm.enclosureFileName = '';
      this.queryForm.enclosureFileUrl = '';
      this.deleting = false;
    },
    // 上传成功
    handleSuccess(res, file, fileList) {
      // console.log(res, file, fileList);
      this.fileList = fileList
      this.queryForm.enclosureFileName = 'a';
      this.deleting = true;
      this.setInformationAttachList(fileList);
    },
    setInformationAttachList(fileList) {
      let attachList = [];
      fileList.forEach(item => {
        if (item.response && item.response.data) {
          const uploadedObj = item.response.data[item.name];
          if (uploadedObj) {
            // const attachObj = {};
            // attachObj.fileName = uploadedObj.fileName;
            // attachObj.fileLacation = uploadedObj.objectkey;
            // attachList.push(attachObj);
            this.queryForm.enclosureFileName = uploadedObj.fileName;
            this.queryForm.enclosureFileUrl = uploadedObj.objectkey;
          }
        }
      });
      // return attachList;
    },
    
  },
  // async
  created() {
    this.getOptions();
    if (this.dataListProp) {
      if (this.dataProp === '新增') {
        this.fileList = [];
        this.queryForm.isEnabled = 1;
      } else {
        this.queryForm = JSON.parse(JSON.stringify(this.dataListProp));
        this.fileList.push({ name: this.dataListProp.enclosureFileName });
      }
    } else {
      this.fileList = [];
      this.queryForm = {};
    }
  }
};
</script>
